const { request, uploadFile2, wxLogin} = require('../../utils/request')
// index.ts
const {
  isLogin,
  getAuthSetting,
  openSettingModal,
  throttle,
  formatYMR_cn
} = require('../../utils/util')
// 获取应用实例
const app = getApp<IAppOption>()
let inviteBannerCloseNumKey = 'index/inviteBannerCloseNum'
let inviteBannerCloseNum = wx.getStorageSync(inviteBannerCloseNumKey) || 0
let hasPlayVoice2 = wx.getStorageSync('hasPlayVoice2') || false
Page({
  data: {
    demoRecord:null,
    hadShowBoardPage: wx.getStorageSync('hadShowBoardPage'),
    hasLogin:true,
    needShowPrivacy: true,
    privacyActionSheetVisible: false,
    noteList: [],
    playingAudioUrl:'', // 正在播放的音频url
    userInfo:null,
    showPrivacy:false,
    noteListScrollTop:-1,
    loading: true,
    showInviteBanner:false,
    showInviteBtn:false,
    inviteBannerCloseNum:inviteBannerCloseNum,  // 邀请banner被关闭次数
    inviteData:{
      status:1, // 1=未完成 2=已完成
      prompt:'邀请5位好友注册，录音延长至3分钟'
    },
    deleteRecordDialogVisible:false,
    curDeleteRecord:null,
    curShareRecord:null,
    weComStatus:3, // 企业微信的绑定状态，1=未关注 2=已关注 3=不展示
    sharePanelVisible:false,
    actionList:[
      {
        id:'delete',
        name:'删除',
      },
      {
        id:'update',
        name:'修改',
      }
    ],
    actionBarVisible:false,
    actionBarPosition:{
      top:'50%',
      left:'50%',
    },
    curPressRecord:null,
    selfDialogData:{
      title:'提示',
      content:'是否删除该录音？',
      cancelText:'取消',
      confirmText:'确定',
      showCancelBtn:true,
      showConfirm:true,
      confirmColor:'#FF6B6B',
      cancelColor:'#333333',
      visible:false,
    },
    actionType:null
  },
  //options(Object)
  onLoad: function () {
    this.setData({
      hadShowBoardPage: wx.getStorageSync('hadShowBoardPage')
    })
    this.getPrivacyStatus()
    
  },

  onShow: function () {
    console.log('onShow')
    hasPlayVoice2 = false
    this.noteListScrollToTarget()
    this.indexlogin()
    // 测试
    // this.testRequest()
  },


  showActionBar(event:any){
    // console.log('showActionBar event:',event)
    let targetData = event.currentTarget.dataset.item
    // 1=未完成 2=已完成
    if(targetData.status !== 2){
      return 
    }
    let touchEvent = event.touches[0]
    
    this.setData({
      actionBarVisible:true,
      curPressRecord:event.currentTarget.dataset.item,
      actionBarPosition:{
        top:`calc(${touchEvent.clientY}px - 82rpx)`,
        left:touchEvent.clientX+'px',
      }
    })
    // console.log('data:',this.data)
  },
  hideActionBar(){
    this.setData({
      actionBarVisible:false
    })
  },
  hideSelfDialog(){
    this.setData({
      selfDialogData:{
        ...this.data.selfDialogData,
        visible:false
      }
    })
  },
  videoEnd(){
    console.log('videoEnd')
    this.hideBoardPage()
  },
  actionTap(event:any){
    // let id = event.currentTarget.dataset.id
    console.log('actionTap event:',event)
    this.hideActionBar()
    let actionType = event.detail
    

    if(actionType ==='delete'){
      let actionName = actionType ==='delete' ? '删除':'修改'
      let selfDialogData = this.data.selfDialogData
      selfDialogData.visible = true
      
      selfDialogData.title="提示"
      selfDialogData.content=`确定要${actionName}这条记录吗？`
      this.setData({
        selfDialogData:selfDialogData,
        actionType:actionType
      })
    }else {
      wx.navigateTo({
        url:'/pages/changeContent/changeContent?id='+this.data.curPressRecord.id
      })
    }
    
    
  },
  confirmActionTap(){
    let actionType = this.data.actionType
    if(actionType ==='delete'){
      this.deleteThisRecord()
    }else if(actionType ==='update'){
      wx.navigateTo({
        url:'/pages/changeContent/changeContent?id='+this.data.curPressRecord.id
      })
    }
  },
  showSharePanel(event:any){
    let curShareRecord = event.currentTarget.dataset.item
  
    this.setData({
      curShareRecord:curShareRecord,
      sharePanelVisible:true
    })
  },
  hideSharePanel(){
    this.setData({
      sharePanelVisible:false
    })
  },
  hideBoardPage(){
    this.setData({
      hadShowBoardPage:true
    })
    wx.setStorageSync('hadShowBoardPage',true)
    // 如果记录为空，则播放音频
    if(this.data.noteList.length==0){
      this.playVoice2()
    }
  },
  async indexlogin(){
    let that = this as any
    if(!isLogin()){
      await wxLogin()
    }
    this.getDemoRecord()
    this.initDataWhenLogin()
    // 获取请求参数
    let launchOptions = wx.getEnterOptionsSync()
    console.log('indexlogin launchOptions:',launchOptions)
    let query = launchOptions.query
    if(query.jtUserId){
      this.bingJingTanUser(query.jtUserId)
    }else {
      // 查询当前用户的邀请任务
      that.getInviteStatus()
      // 获取企业微信绑定状态
      that.getWeComStatus()
    }
  },
  showDeleteRecordDialog(event:any){
    let item = event.currentTarget.dataset.item
    this.setData({
      deleteRecordDialogVisible:true,
      curDeleteRecord:item
    })
  },
  hideDeleteRecordDialog(){
    this.setData({
      deleteRecordDialogVisible:false
    })
  },
  deleteThisRecord(){
    let curDeleteRecord = this.data.curPressRecord
    // 如果录音正在播放，则停止播放录音
    if(this.data.playingAudioUrl === curDeleteRecord.voiceAddress){
      this.stopAllAudio()
    }
    request({
      url:'/records/'+curDeleteRecord.id,
      method:'delete',
      success:()=>{
        wx.showToast({
          title:'删除成功',
          icon:'success',
          duration:1500
        })
        this.getHistoryRecord()
        
      }
    })
  },
  initDataWhenLogin(){
    let that = this as any
    // 获取历史日志数据
    that.getHistoryRecord()
    // 重新查询用户信息
    that.getUserInfo()
    
  },
   // 绑定鲸探用户
   bingJingTanUser(jtUserId:string){
    let that = this as any
    request({
      url: '/users/jingtan-bind?jingtanId='+jtUserId,
      method: 'POST',
      data:{
        jingtanId:jtUserId
      },
      success: function (res:any) {
        console.log('jingtan res:',res)
        
        setTimeout(()=>{
          // 查询当前用户的邀请任务
          that.getInviteStatus()
          // 获取企业微信绑定状态
          that.getWeComStatus()
          that.getUserInfo()
        },300)
      },
      fail(err:any){
        console.log('error:',err)
      }
    })
  },
  getWeComStatus(){
    request({
      url:'/users/e-wechat/follow-status?env=' + (app.globalData.isDev ? 2 : 1),
      success:(data:any)=>{
        // console.log('getWeComStatus data:',data)
        this.setData({
          weComStatus: data.status
        })
      }
    })
  },
 
  getInviteStatus(){
    // 获取当前用户邀请任务
    let that = this as any
    request({
      url:'/ui-task/current',
      success:(data:any)=>{
        // console.log('getInviteStatus data:',data)
        that.setData({
          inviteData:data
        },()=>{
          
          that.judgeShowInvite()
        })
      }
    })
  },

  jumpTemplatePage(eventOrItem:any){
    let that = this
    console.log('jumpTemplatePage eventOrItem:',eventOrItem)
    let isNewRecord = eventOrItem && eventOrItem.currentTarget ? false : true
    let recordData = isNewRecord ? eventOrItem : eventOrItem.currentTarget.dataset.item
    wx.navigateTo({
      url:'/pages/template/template?id='+recordData.id+'&shareChannel=2'
    })

    wx.setStorageSync('/index/templateData',{
      title:recordData.title,
      content:recordData.content
    })
    
  },

  judgeShowInvite(){
    // 判断如何显示邀请弹窗和按钮
    let inviteBannerCloseNum = this.data.inviteBannerCloseNum
    // console.log('inviteBannerCloseNum:',inviteBannerCloseNum)
    let status = this.data.inviteData.status
    // console.log('judgeShowInvite status:',status)
    if(status ===2){
      // 已完成邀请任务，则全部隐藏
      this.setData({
        showInviteBanner: false,
        showInviteBtn: false
      })
    }else {
      // 未完成邀请任务
      this.setData({
        showInviteBanner: inviteBannerCloseNum < 3,
        showInviteBtn: inviteBannerCloseNum >= 3
      })
    }
    
  },
  showInviteBanner(){
    this.setData({
      showInviteBanner:true,
      showInviteBtn:false
    })
  },
  hideInviteBanner(){
    console.log('hideInviteBanner')
    let inviteBannerCloseNum = this.data.inviteBannerCloseNum
    inviteBannerCloseNum = inviteBannerCloseNum + 1
    this.setData({
      showInviteBanner:false,
      showInviteBtn:true,
      inviteBannerCloseNum
    })
    wx.setStorageSync(inviteBannerCloseNumKey,inviteBannerCloseNum)
    
  },
  getPrivacyStatus(){
    // 检查用户是否同意了隐私协议
    wx.getPrivacySetting({
      success: (res) => {
        // console.log('getPrivacySetting res:',res)
        // alert('getPrivacySetting res:' + JSON.stringify(res))
        if (res.needAuthorization) {
          // 需要弹出隐私协议
          this.setData({
            needShowPrivacy: true
          })
        } else {
          this.setData({
            needShowPrivacy: false
          })
        }
      },
      fail: (error) => {
        // alert('getPrivacySetting error:' + JSON.stringify(error))
      },
      complete: () => {}
    })
  },
  stopAllAudio(){
    this.setData({
      playingAudioUrl:'stopAll'
    })
  },
  resolveLoading(callback:any){
    setTimeout(()=>{
      this.setData({
        loading:false
      },()=>{
        callback && callback()
      })
    },100)
  },
  getUserInfo(){
    request({
      url:'/users/current-user',
      method:'GET',
      success:(data:any)=>{
        this.setData({
          userInfo:data,
        })
        console.log('getUserInfo:',data)
        wx.setStorageSync('userInfo',data)
      },
      complete:()=>{
        this.resolveLoading()
      }
    })
  },
  postShareData(){
    let curShareRecord = this.data.curShareRecord
    console.log('curShareRecord:',curShareRecord)
    return new Promise((resolve)=>{
      request({
        url:'/record-share',
        method:'POST',
        data:{
          recordId: curShareRecord.id,
          templateCode:'riji'
        },
        success(rData:any){
          let shareData = app.getDefaultShareData()
          let userInfo = wx.getStorageSync('userInfo')
          let userId = (userInfo && userInfo.id) || ''
          resolve({
            title: '我记了一篇日记，快来看看吧',
            imageUrl: shareData.imageUrl,
            path:'/pages/share/share?inviteUserId='+userId+'&shareChannel=2&id='+rData.id,
          })
        }
      })
    })
  },
  onShareAppMessage(){
    return {
      ...app.getDefaultShareData(),
      promise: this.postShareData()
    }
  },
  onShareTimeline(){
    return {
      ...app.getDefaultShareData(),
      promise: this.postShareData()
    }
  },

  
  playThisAudio(event:any){
    // console.log('playThisAudio:',event.detail.audioUrl)
    this.setData({
      playingAudioUrl: event.detail.audioUrl
    })
  },
  jumpSettingPage(){
    wx.navigateTo({
      url:'/pages/setting/setting'
    })
  },
  formatToday(dateStr:string):any{
    if(dateStr){
      // 将日期格式化成ios可以识别的格式
      dateStr = dateStr.replace(/-/g,'/')
      var now = new Date()
      var tempDate = new Date(dateStr)
      if(now.getFullYear() == tempDate.getFullYear() && now.getMonth() === tempDate.getMonth() && now.getDate() === tempDate.getDate()){
        return '今天'
      }else{
        return formatYMR_cn(dateStr)
      }
    }
  },
  // 获取示范记录
  getDemoRecord(){
    let that = this
    request({
      url:'/sys/demo-record',
      method:'GET',
      success:(data:any)=>{
        that.setData({
          demoRecord:data
        })
      }
    })
  },
  getHistoryRecord(){
    let that = this
    // 获取历史日志数据
    request({
      url:'/user-records',
      method:'GET',
      success:(data:any)=>{
        data.forEach((item:any)=>{
          item.recordDate = that.formatToday(item.recordDate)
        })
        that.setData({
          noteList:data
        })
        if(data.length === 0){
          // 如果显示引导页，就先不播放音频
          if(that.data.hadShowBoardPage){
            this.resolveLoading(that.playVoice2.bind(that))
          }else {
            this.resolveLoading()
          }
          
        }
   
      },
      
    })
  },

 
  stopTouchmove(event:any){
    return false
  },
 
 
  testUpload(){
    wx.chooseMedia({
      count:1,
      mediaType:['image'],
      success:(res:any)=>{
        console.log('tempFiles:',res.tempFiles)
        let tempFile = res.tempFiles[0]
        
        uploadFile2(tempFile.tempFilePath)
      }
    })
  },


  noteListScrollToTarget(){
    this.setData({
      noteListScrollTop:0
    },()=>{
      this.setData({
        noteListScrollTop:-1
      })
    })
  },

  hidePrivacyActionSheet() {
    this.setData({
      privacyActionSheetVisible: false,
    })
  },
  rejectPrivacy(){
    this.hidePrivacyActionSheet()
    wx.exitMiniProgram()
  },
  showPrivacyActionSheet() {
    // 显示用户隐私协议
    this.setData({
      privacyActionSheetVisible: true
    })
  },
  
  jumpToRecordPage(){
    console.log('jumpToRecordPage')
    wx.navigateTo({
      url:'/pages/record/record'
    })
  },

  playVoice1(){
    let comVoice1 = this.selectComponent('#syVoice1')
    let comVoice2 = this.selectComponent('#syVoice2')
    comVoice1 && comVoice1.playVoice();
    comVoice2 && comVoice2.stopVoice();
  },
  playVoice2(){
    let comVoice1 = this.selectComponent('#syVoice1')
    let comVoice2 = this.selectComponent('#syVoice2')
    // console.log('comVoice1:',comVoice1)
    console.log('hasPlayVoice2:',hasPlayVoice2)
    if(!hasPlayVoice2){
      comVoice1 && comVoice1.stopVoice();
      comVoice2 && comVoice2.playVoice();
    }
    hasPlayVoice2 = true
    
  },
  authRecord:throttle(async function (){
    this.stopAllAudio()
    
    getAuthSetting('scope.record', this.jumpToRecordPage, () => {
      openSettingModal('提示', '请先开启麦克风权限', '去开通')
    })
  },2000),

  jumpPublicAccountPage() {
    wx.navigateTo({
      url: '/pages/wecom/wecom'
    })
  },




  agreePrivacyAuthorization() {
    // 用户同意隐私协议
    console.log('用户同意隐私协议')
    this.stopAllAudio()
    
    // 弹出隐私协议弹窗
    // this.showPrivacyActionSheet()
    // this.setData({
    //   needShowPrivacy: false
    // })
    this.authRecord()
  },
  jumpArticle(event: any) {
    const id = event.currentTarget.dataset.id
    wx.navigateTo({
      url: '/pages/article/article?id=' + id
    })
  },
  testRequest(){
    wx.request({
      url:'https://d-record-api.wanhuhealth.com/wechatapp/unionid',
      method:'POST',
      success(res){
        console.log('testRequest res:',res)
      },
      fail(err){
        console.log('testRequest err:',err)
      }
    })
  }
})
export {}
